package com.baosight.risk.service.zbaa.impl;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.rire.RiwaRiskWaringService;
import com.baosight.risk.api.xtaa.code.IXtaaCodeService;
import com.baosight.risk.api.xtaa.sequences.IXtaaSequencesService;
import com.baosight.risk.api.zbaa.IZbaaTargetService;
import com.baosight.risk.api.zbaa.IZbaaTargetValueService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.Status;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.HttpUtils;
import com.baosight.risk.common.utils.ReadProperties;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.zbaa.ZbaaTargetMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetSendMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetUnitMapper;
import com.baosight.risk.mapper.zbaa.ZbaaTargetValueMapper;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.baosight.risk.service.xtaa.code.vo.PersonTargetTreeVO;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.service.zbaa.entity.ZbaaTarget;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetSend;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetUnit;
import com.baosight.risk.service.zbaa.entity.ZbaaTargetValue;
import com.baosight.risk.service.zbaa.vo.TargetVO;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetHomeIndexVO;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetVO;
import com.baosight.risk.service.zbaa.vo.ZbaaTargetValueVO;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ZbaaTargetServiceImpl extends BaseServiceImpl<ZbaaTarget> implements IZbaaTargetService {

    @Autowired
    private ZbaaTargetMapper targetMapper;
    @Autowired
    private ZbaaTargetUnitMapper targetUnitMapper;
    @Autowired
    private ZbaaTargetSendMapper targetSendMapper;
    @Autowired
    private ZbaaTargetValueMapper targetValueMapper;
    @Autowired
    private IXtaaCodeService codeService;

    @Autowired
    private IXtaaSequencesService sequencesService;

    @Autowired
    private IZbaaTargetValueService zbaaTargetValueService;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private IXtaaCodeService xtaaCodeService;

    @Autowired
    private RiwaRiskWaringService waringService;

    @Override
    public BaseMapper getMapper() {
        return targetMapper;
    }


    @Override
    public Integer insertTarget(ZbaaTargetVO target) {
        //根据选择的风险指标，获取根节点指标编号
        XtaaCode xtaaCode = codeService.selectXtaaCodeByDDCodeAndEndLevel(target.getTargetType());

        String parrentXtaaCodeName = codeService.selectParentXtaaCodeNameByXtaaCode(xtaaCode);
        //区分内部指标外部指标信息
        if (parrentXtaaCodeName.equals("ZBN")) {
            target.setRiskSource("N");
            target.setRiskSourceName("内部指标");
        }
        if (parrentXtaaCodeName.equals("ZBW")) {
            target.setRiskSource("W");
            target.setRiskSourceName("外部指标");
        }
        //初始化基本参数
        target = (ZbaaTargetVO) BeanUtils.initBean(target);
        //直接新增的时候，编码是空的，需要获取编码，复制新增的是有编码的，不需要获取编码
        if (StringUtils.isEmpty(target.getTargetNo())) {
            //根据节点编码区分内部外部流水号
            //指标的编码根据不进行分组流水，第一个参数为空
            String code = sequencesService.generateCodeById(null, "zbaaTarget_" + parrentXtaaCodeName, "", "", "");
            target.setTargetNo(code);
        }
        if (StringUtils.isEmpty(target.getCompCode())) {
            target.setCompCode("all");
        }
        //新创建的风险指标默认状态草稿
        target.setStatus(Status.DRAFT.getValue());
        target.setStatusName(Status.DRAFT.getDescription());
        log.info("风险指标添加参数：" + target.toString());
        Integer row = targetMapper.insert(target);
        if (CollectionUtils.isNotEmpty(target.getUnitList())) {
            for (ZbaaTargetUnit zbaaTargetUnit : target.getUnitList()) {
                zbaaTargetUnit.setTargetId(target.getId());
                zbaaTargetUnit = (ZbaaTargetUnit) BeanUtils.initBean(zbaaTargetUnit);
                targetUnitMapper.insert(zbaaTargetUnit);
            }
        }
        return row;
    }

    @Override
    public Integer updateTarget(ZbaaTargetVO target) {
        targetUnitMapper.deleteByTarget(target.getId());
        if (CollectionUtils.isNotEmpty(target.getUnitList())) {
            for (ZbaaTargetUnit zbaaTargetUnit : target.getUnitList()) {
                zbaaTargetUnit.setTargetId(target.getId());
                zbaaTargetUnit = (ZbaaTargetUnit) BeanUtils.initBean(zbaaTargetUnit);
                targetUnitMapper.insert(zbaaTargetUnit);
            }
        }
        return targetMapper.updateByPrimaryKey(target);
    }

    @Override
    public ZbaaTargetVO getById(String id) {
        ZbaaTargetVO targetVO = new ZbaaTargetVO();
        ZbaaTarget target = targetMapper.selectByPrimaryKey(id);
        BeanUtils.copyBeanProp(targetVO, target);
        targetVO.setUnitList(targetUnitMapper.selectByTargetId(id));
        return targetVO;
    }


    @Override
    public ZbaaTarget getTargetByTargetNo(String targetNo) {
        return targetMapper.getTargetByTargetNo(targetNo);
    }

    @Override
    public List<ZbaaTarget> getTargetList(ZbaaTarget target) {
        //查询所有指标数据
        return targetMapper.getTargetList(target);
    }

    /**
     * 判断当前数据该用户是否已经订阅，如果已经订阅，ext1的数据为1，否则为空
     *
     * @param targetList
     * @param userCode
     */
    public void sendInfo(List<ZbaaTarget> targetList, String userCode) {
        List<ZbaaTargetSend> sendList = targetSendMapper.selectSend(userCode);
        if (!CollectionUtils.isEmpty(sendList)) {
            for (ZbaaTarget zbaaTarget : targetList) {
                //默认订阅字段设置为0
                zbaaTarget.setExt1("0");
                for (ZbaaTargetSend send : sendList) {
                    if (zbaaTarget.getId().equals(send.getTargetId())) {
                        //表示当前登陆人已经订阅该数据
                        zbaaTarget.setExt1("1");
                        continue;
                    }
                }
            }
        }
    }


    @Override
    public List<ZbaaTarget> getTargetListByUser(XtzyUser user, String targetName) {
        return targetMapper.getTargetByUser(user.getUserCode(), targetName);
    }

    @Override
    public String addOrder(ZbaaTargetSend targetSend, XtzyUser user) {
        // 判断是否订阅该指标
        List<ZbaaTargetSend> sendList = targetSendMapper.selectSend(user.getUserCode());
        for (ZbaaTargetSend zbaaTargetSend : sendList) {
            if (zbaaTargetSend.getTargetNo().equals(targetSend.getTargetNo()) && zbaaTargetSend.getCompCode().equals(targetSend.getCompCode())) {
                return "当前用户已经订阅该指标，无需重复订阅！";
            }
        }

        //初始化基本参数
        targetSend = (ZbaaTargetSend) BeanUtils.initBean(targetSend);
        targetSend.setUserCode(user.getUserCode());
        targetSend.setUserDesc(user.getUserDesc());
        targetSendMapper.insert(targetSend);
        return "订阅成功";
    }

    @Override
    public Integer deleteOrder(List<String> ids) {
        return targetSendMapper.deleteOrder(ids);
    }


    @Override
    public List<ZbaaTarget> getTargetByIds(List<String> ids) {
        return targetMapper.getTargetByIds(ids);
    }

    @Override
    public List<ZbaaTarget> getTargetListByTagertTypes(ZbaaTarget target, List<String> types, XtzyUser user) {
        List<ZbaaTarget> targetList = targetMapper.getTargetListByTagertTypes(target, types);
        sendInfo(targetList, user.getUserCode());
        return targetList;
    }

    @Override
    public Integer updateStatus(List<String> ids, String status, String statusName) {
        return targetMapper.updateStatus(ids, status, statusName);
    }

    @Override
    public Integer externalInterface() throws Exception {
        List<Map<String, String>> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("targetNo", "123456");
        map.put("standardValue", "9876");
        map.put("targetValue", "5432");
        map.put("duration", "1234");
        list.add(map);
        Map<String, Object> maps = new HashMap<>();
        maps.put("data", list);

        log.info("================" + JSONObject.fromObject(maps));

        String url = ReadProperties.getValueString("python.predict.url");
        //调用外部接口获取数据
        String result = HttpUtils.sendJsonPost(url, JSONObject.fromObject(maps));

//        JSONObject json = JSONObject.fromObject(result);
//        System.out.println("=============="+json);
////        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        JSONArray array = JSONArray.fromObject(json.get("data"));
//        //接受外部数据
//        List<TargetVO> targetVOList = JSONArray.toList(array, new TargetVO(), new JsonConfig());
//        if (!CollectionUtils.isEmpty(targetVOList)) {
//                     target.setTargetName(targetVO.getName());
////                //todo：指标类型待定，确认后需要改变      for (TargetVO targetVO : targetVOList) {
//                ZbaaTarget target = new ZbaaTarget();
//
//                target.setTargetType("1");
//                target.setTargetTypeName("外部指标");
//                target = (ZbaaTarget) BeanUtils.initBean(target);
//                targetMapper.insert(target);
//                //新增指标值
//                if (!CollectionUtils.isEmpty(targetVO.getValuelist())) {
//                    for (TargetVO.Vaule vaule : targetVO.getValuelist()) {
//                        ZbaaTargetValue targetValue = new ZbaaTargetValue();
//                        targetValue.setTargetNo(target.getId());
//                        targetValue.setTargetValue(vaule.getValue());
//                        targetValue = (ZbaaTargetValue) BeanUtils.initBean(targetValue);
//                        targetValue.setCreateTime(sdf.parse(vaule.getDate()));
//                        targetValueMapper.insert(targetValue);
//                    }
//                }
//            }
//        }
        return 1;
    }

    @Override
    public List<TargetVO> getHistory(List<String> targetIds, Integer count) {
        //日期格式转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<TargetVO> targetVOS = new ArrayList<TargetVO>();
        //如果传进来就一个且为0 ，查询所有数据
        if ("0".equals(targetIds.get(0))) {
            List<ZbaaTarget> targetList = targetMapper.selectAll();
            targetIds = targetList.stream().map(ZbaaTarget::getTargetNo).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(targetIds)) {
            return null;
        }
        //遍历获得ZbaaTargetValue对象进行数据填充
        for (String targetId : targetIds) {
            TargetVO targetVO = new TargetVO();
            targetVO.setTargetId(targetId);
            List<TargetVO.Vaule> vauleList = new ArrayList<>();
            List<ZbaaTargetValue> history;
            //如果count=0，代表查所有数据
            if (count > 0) {
                history = targetValueMapper.getHistory(targetId, count);
            } else {
                history = targetValueMapper.getAllHistory(targetId);
            }

            for (ZbaaTargetValue zbaaTargetValue : history
            ) {
                TargetVO.Vaule vaule = targetVO.new Vaule();
                vaule.setValue(zbaaTargetValue.getTargetValue());
                vaule.setDate(sdf.format(zbaaTargetValue.getCreateTime()));
                targetVO.setName(zbaaTargetValue.getTargetName());
                vauleList.add(vaule);
            }
            targetVO.setValuelist(vauleList);
            targetVOS.add(targetVO);
        }
        return targetVOS;
    }

    public String getTargrtValue(Date date, String targetNo, String compCode, String val) {
        if (null == date) {
            date = new Date();//获取当前时间
        }
        //计算结果都是前一天的，所以日期减1
        Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例
        calendar.setTime(date);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1); //当前时间减去一天，即一天前的时间
        String riqi = DateUtils.format(calendar.getTime(), "yyyyMMdd");
        //年
        Integer year = Integer.valueOf(riqi.substring(0, 4));
        //月
        String mouth = riqi.substring(4, 6);
        //季
        Integer quarter = Integer.valueOf(DateUtils.getQuarter(calendar.getTime()));
        //月度天数
        Integer dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //季度月份
        List<String> mouthList = new ArrayList<>();
        //查找标志
        String flag = "";
        if (StringUtils.isNotEmpty(val)) {
            switch (val) {
                case "0M01":
                    //月度最后一天（本月最后一天）
                    flag = year.toString() + riqi.substring(4, 6) + dayCount.toString();
                    break;
                case "0Q01":
                    //季度最后一天（本季度最后一天）
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    mouth = mouthList.get(mouthList.size() - 1);
                    if ("03".equals(mouth) || "12".equals(mouth)) {
                        flag = year.toString() + mouth + "31";
                    } else {
                        flag = year.toString() + mouth + "30";
                    }
                    break;
                case "0Q02":
                    //季度最后一个月（本季度最后一月）
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    mouth = mouthList.get(mouthList.size() - 1);
                    flag = year.toString() + mouth;
                    break;
                case "0Q03":
                    //本季度平均值
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    mouthList.add("Q" + quarter.toString());
                    return targetValueMapper.getAverageValue(targetNo, compCode, year.toString(), mouthList);
                case "0Y01":
                    //年度最后一天
                    flag = year.toString() + "1231";
                    break;
                case "LQ01":
                    //上季度最后一天
                    if (1 == quarter) {
                        year = year - 1;
                        quarter = 4;
                    } else {
                        quarter = quarter - 1;
                    }
                    mouth = riqi.substring(4, 6);
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    if ("03".equals(mouth) || "12".equals(mouth)) {
                        flag = year.toString() + mouthList.get(mouthList.size() - 1) + "31";
                    } else {
                        flag = year.toString() + mouthList.get(mouthList.size() - 1) + "30";
                    }
                    break;
                case "LM01":
                    //上月度最后一天
                    calendar.add(Calendar.MONTH, -1);//当前时间前去一个月，即一个月前的时间
                    riqi = DateUtils.format(calendar.getTime(), "yyyyMMdd");
                    dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    flag = riqi.substring(0, 6) + dayCount.toString();
                    break;
                case "LY01":
                    //上年度最后一天
                    year = year - 1;
                    flag = year.toString() + "1231";
                    break;
                case "LY02":
                    //上年本月
                    year = year - 1;
                    flag = year + mouth;
                    break;
                default:
                    //最新的数据
                    break;
            }
        }
        return targetValueMapper.getLatestValue(targetNo, compCode, flag, null);
    }

    /**
     * @param targetNo  指标编号
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param period    范围周期
     * @return 指标值
     * @description 获取数据，空数据补"-"
     * @author CuiShiHao
     */
    @Override
    public List<ZbaaTargetValueVO> getValue(String targetNo, List<String> compCodeList, String startTime, String endTime, String period) {

//        String start = startTime.replaceAll("-", "");
//        String end = endTime.replaceAll("-", "");
        //获取过滤日期范围
        List<String> RangeList = DateUtils.getRangeList(startTime, endTime, period);
        String start="";
        String end="";
        if(StringUtils.isNotEmpty(startTime)){
            start=startTime.replace("-","");
        }
        if(StringUtils.isNotEmpty(endTime)) {
            end = endTime.replace("-", "");
        }


        //获取全部单位数据
        List<ZbaaTargetValue> dataResult = targetValueMapper.getValue(targetNo, null, compCodeList, start, end);
        //按照单位分组
        Map<String, List<ZbaaTargetValue>> groupByComp = dataResult.stream().collect(Collectors.groupingBy(ZbaaTargetValue::getCompCode));

        //遍历分组,拼接返还结果
        List<ZbaaTargetValueVO> finalResult = new ArrayList<>();
        for (Map.Entry<String, List<ZbaaTargetValue>> dataEntry : groupByComp.entrySet()) {

            List<ZbaaTargetValue> dataList = dataEntry.getValue();
            //对数据进行后处理（重复的数据周期范围仅取一条，无数据补充0值）
            if (dataResult != null && dataResult.size() != 0) {

                ZbaaTargetValueVO zbaaTargetValueVO = new ZbaaTargetValueVO();
                zbaaTargetValueVO.setTargetName(dataList.get(0).getTargetName());
                zbaaTargetValueVO.setTargetNo(dataList.get(0).getTargetNo());
                zbaaTargetValueVO.setCompName(dataList.get(0).getCompName());
                zbaaTargetValueVO.setCompCode(dataList.get(0).getCompCode());
                zbaaTargetValueVO.setUnit(dataList.get(0).getUnit());
                List<ZbaaTargetValue> zbaaTargetValueList = new ArrayList<>();

                //对数据进行后处理
                for (int i = 0; i < RangeList.size(); i++) {
                    ZbaaTargetValue zbaaTargetValue = new ZbaaTargetValue();
                    zbaaTargetValue.setTargetName(dataList.get(0).getTargetName());
                    zbaaTargetValue.setCompCode(dataList.get(0).getCompCode());
                    zbaaTargetValue.setCompName(dataList.get(0).getCompName());
                    zbaaTargetValue.setUnit(dataList.get(0).getUnit());
                    zbaaTargetValue.setPeriodNo(RangeList.get(i));
                    zbaaTargetValue.setTargetValue("-");
                    //遍历原数据后赋值
                    for (ZbaaTargetValue targetValue : dataList) {
                        if (targetValue.getPeriodNo().equals(RangeList.get(i))) {
                            zbaaTargetValue.setTargetValue(targetValue.getTargetValue());
                            break;
                        }
                    }
                    zbaaTargetValueList.add(zbaaTargetValue);
                }
                zbaaTargetValueVO.setDataList(zbaaTargetValueList);
                finalResult.add(zbaaTargetValueVO);
            }
        }
        return finalResult;
    }

    /**
     * @param targetNo  指标编号
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param period    范围周期
     * @return 指标值
     * @description 获取数据(仅首页获取数据使用)
     * @author CuiShiHao
     */
    @Override
    public List<ZbaaTargetValueVO> getHomeValue(String targetNo, List<String> sysSourceList, String startTime, String endTime, String period) {

        String start = startTime.replaceAll("-", "");
        String end = endTime.replaceAll("-", "");
        //获取过滤日期范围
        List<String> rangeList = DateUtils.getRangeList(startTime, endTime, period);
        //获取全部单位数据
        List<ZbaaTargetValue> dataResult = new ArrayList<>();
        //区分开ZBW0106 的两种数据
        if ("ZBW0106".equals(targetNo)){
            ArrayList<String> strings = new ArrayList<>();
            strings.add("BGTA");
            dataResult =targetValueMapper.getValue(targetNo, sysSourceList,strings, start, end);
        }else{
            dataResult =targetValueMapper.getValue(targetNo, sysSourceList, null, start, end);
        }

        //按照单位分组
        Map<String, List<ZbaaTargetValue>> groupByComp = dataResult.stream().collect(Collectors.groupingBy(ZbaaTargetValue::getSysSource));

        //遍历分组,拼接返还结果
        List<ZbaaTargetValueVO> finalResult = new ArrayList<>();
        for (Map.Entry<String, List<ZbaaTargetValue>> dataEntry : groupByComp.entrySet()) {

            List<ZbaaTargetValue> dataList = dataEntry.getValue();
            //对数据进行后处理（重复的数据周期范围仅取一条，无数据补充0值）
            if (dataResult != null && dataResult.size() != 0) {

                // 判断当前指标是否需要按照工作日处理
                ZbaaTarget zbaaTarget = targetMapper.getTargetByTargetNo(targetNo);
                String isWorkDay = zbaaTarget.getIsWorkDay();

                ZbaaTargetValueVO zbaaTargetValueVO = new ZbaaTargetValueVO();
                zbaaTargetValueVO.setTargetName(dataList.get(0).getTargetName());
                zbaaTargetValueVO.setTargetNo(dataList.get(0).getTargetNo());
                zbaaTargetValueVO.setSource(dataList.get(0).getSysSource());
                zbaaTargetValueVO.setUnit(dataList.get(0).getUnit());
                zbaaTargetValueVO.setCreateTime(dataList.get(0).getCreateTime());
                zbaaTargetValueVO.setDefinition(zbaaTarget.getTargetDesc());
                List<ZbaaTargetValue> zbaaTargetValueList = new ArrayList<>();

                //对数据进行后处理
                for (int i = 0; i < rangeList.size(); i++) {
                    ZbaaTargetValue zbaaTargetValue = new ZbaaTargetValue();
                    zbaaTargetValue.setTargetName(dataList.get(0).getTargetName());
                    zbaaTargetValue.setSysSource(dataList.get(0).getSysSource());
                    zbaaTargetValue.setSysSourceName(dataList.get(0).getSysSourceName());
                    zbaaTargetValue.setUnit(dataList.get(0).getUnit());
                    zbaaTargetValue.setPeriodNo(rangeList.get(i));
                    zbaaTargetValue.setTargetValue("0");

                    // 遍历原数据后赋值
                    String range = rangeList.get(i);
                    List<ZbaaTargetValue> list = dataList.stream().filter(targetValue -> targetValue.getPeriodNo().equals(range)).collect(Collectors.toList());
                    if (list.size() > 0) {
                        // 有数据集则将第一条数据作为真实数据插入
                        zbaaTargetValue.setTargetValue(list.get(0).getTargetValue());
                        zbaaTargetValueList.add(zbaaTargetValue);
                        continue;
                    } else {
                        //  若为工作日则跳过空数据
                        if (isWorkDay.equals("Y") && period.equals("日")) {
                            continue;
                        }
                        // 非工作日则对数据补0
                        zbaaTargetValueList.add(zbaaTargetValue);
                        continue;
                    }
                }
                zbaaTargetValueVO.setDataList(zbaaTargetValueList);
                finalResult.add(zbaaTargetValueVO);
            }
        }
        return finalResult;
    }


    @Override
    public String getTargetValue(String targetNo, String compCode) {
//        //月度最后一天
//        String value1 = getTargrtValue(targetNo,compCode,"0M01");
//        System.out.println("月度最后一天"+value1);
//        //季度最后一天
//        String value2 = getTargrtValue(targetNo,compCode,"0Q01");
//        System.out.println("季度最后一天"+value2);
//        //季度最后一个月
//        String value3 = getTargrtValue(targetNo,compCode,"0Q02");
//        System.out.println("季度最后一个月"+value3);
//        //季度平均值
//        String value4 = getTargrtValue(targetNo,compCode,"0Q03");
//        System.out.println("季度平均值"+value4);
//        //年度最后一天
//        String value5 = getTargrtValue(targetNo,compCode,"0Y01");
//        System.out.println("年度最后一天"+value5);
//        //上月度最后一天
//        String value6 = getTargrtValue(targetNo,compCode,"LM01");
//        System.out.println("上月度最后一天"+value6);
        //上季度最后一天
        String value = getTargrtValue(new Date(), targetNo, compCode, "LQ01");
//        System.out.println("上季度最后一天"+value);
//        //上年度最后一天
//        String value8 = getTargrtValue(targetNo,compCode,"LY01");
//        System.out.println("上年度最后一天"+value8);

        //没找到数据就找上季度最后一条数据
        if (StringUtils.isEmpty(value)) {
            //查询上季度最后一条数据
            Integer quarter = Integer.valueOf(DateUtils.getQuarter(new Date())) - 1;
            //获取季度月份
            List<String> mouth = new ArrayList<>();
            DateUtils.getQuarterMouth(quarter, mouth);
            mouth.add("Q" + quarter.toString());
            value = targetValueMapper.getLatestValue(targetNo, compCode, null, mouth);
        }
        if (StringUtils.isEmpty(value)) {
            value = targetValueMapper.getLatestValue(targetNo, compCode, null, null);
        }
        return value;

//       //补年度和月度数据
//        List<ZbaaTargetValue> valueList = targetValueMapper.selectAll();
//        for (ZbaaTargetValue targetValue : valueList) {
//            if ("month".equals(targetValue.getTargetPeriod()) ||
//                    "day".equals(targetValue.getTargetPeriod())){
//                if(StringUtils.isNotEmpty(targetValue.getPeriodNo()) && targetValue.getPeriodNo().length()>=6){
//                    String year = targetValue.getPeriodNo().substring(0,4);
//                    String mouth = targetValue.getPeriodNo().substring(4,6);
//                    targetValue.setAcctYear(year);
//                    targetValue.setAcctPeriod(mouth);
//                    targetValueMapper.updateByPrimaryKeySelective(targetValue);
//                }
//
//            }
//        }
//        return "1";
    }

    private Map<String, Object> getReferenceTarget(String targetNo, String compCode, String acctYear, String quarterCode) {
        ZbaaTarget target = targetMapper.getTargetByTargetNo(targetNo);
        String periodNo = "";
        String periodType = target.getTargetPeriod();
        List<String> periodList = new ArrayList<>();
        Map<String, Object> map = Maps.newHashMap();
        switch (periodType) {
            case "quarter":
                periodNo = acctYear + "Q" + quarterCode;
                periodList.add(periodNo);
                break;
            case "day":
            case "month":
                String[] mouthStr = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
                Integer quarter = Integer.valueOf(quarterCode).intValue();
                int endMouth = quarter * 3;
                periodList.add(acctYear + mouthStr[endMouth - 3]);
                periodList.add(acctYear + mouthStr[endMouth - 2]);
                periodList.add(acctYear + mouthStr[endMouth - 1]);
                periodNo = acctYear + mouthStr[endMouth - 1];
                map.put("mouth", mouthStr[endMouth - 1]);
                break;
            case "year":
                periodNo = acctYear;
                periodList.add(periodNo);
                break;
        }
        ZbaaTargetValue targetValue = targetValueMapper.getReferenceValue(targetNo, compCode, periodList, periodType);
        if (targetValue != null) {
            map.put("id", targetValue.getId());
            map.put("value", targetValue.getTargetValue());
        } else {
            map.put("id", "");
            map.put("value", "");
        }
        map.put("periodNo", periodNo);
        map.put("periodType", periodType);
        map.put("periodList", periodList);
        map.put("target", target);
        return map;
    }

    @Override
    public String getReferenceValue(String targetNo, String compCode, String acctYear, String quarterCode) {
        Map<String, Object> map = getReferenceTarget(targetNo, compCode, acctYear, quarterCode);
        String value = ObjectUtils.toString(map.get("value"), "");
        return value;
    }

    @Override
    public Integer updateReferenceValue(String targetNo, String targetName, String compCode, String acctYear, String quarterCode, String targetValue) {
        Integer result = 0;
        Map<String, Object> map = getReferenceTarget(targetNo, compCode, acctYear, quarterCode);
        String id = ObjectUtils.toString(map.get("id"), "");
        String value = ObjectUtils.toString(map.get("value"), "");
        if (StringUtils.isBlank(id)) {
            // 新增指标值
            ZbaaTarget target = (ZbaaTarget) map.get("target");
            if (target != null) {
                ZbaaTargetValue targetValueModel = new ZbaaTargetValue();
                BeanUtils.copyBeanProp(targetValueModel, target);
                BeanUtils.initBean(targetValueModel);
                targetValueModel.setTargetName(targetName);
                targetValueModel.setTargetValue(targetValue);
                // 设置 PERIOD_NO/
                String periodNo = ObjectUtils.toString(map.get("periodNo"), "");
                String periodType = ObjectUtils.toString(map.get("periodType"), "");
                if (periodType.equals("day") || periodType.equals("month")) {
                    String mouth = ObjectUtils.toString(map.get("mouth"), "");
                    targetValueModel.setAcctPeriod(mouth);
                    if (periodType.equals("day")) {
                        Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例
                        calendar.set(calendar.YEAR, Integer.valueOf(acctYear).intValue());
                        calendar.set(calendar.MONTH, (Integer.valueOf(quarterCode).intValue() * 3) - 1);
                        Integer dayCount = calendar.getActualMaximum(Calendar.DATE);   //月度天数
                        periodNo = periodNo + dayCount;
                    }
                }
                targetValueModel.setPeriodNo(periodNo);
                targetValueModel.setAcctYear(acctYear);
                targetValueModel.setUpdateBy(null);
                targetValueModel.setUpdateTime(null);
                targetValueModel.setExt1(null);
                targetValueModel.setExt2(null);
                targetValueModel.setExt3(null);
                targetValueModel.setExt4(null);
                targetValueModel.setExt5(null);
                List<ZbaaTargetValue> list = new ArrayList<>();
                list.add(targetValueModel);
                zbaaTargetValueService.insertValueList(list);
            }
        } else if (!StringUtils.equals(value, targetValue)) {
            // 修改指标值
            result = targetValueMapper.updateReferenceValue(id, targetValue);
        }
        return result;
    }

    @Override
    public void getUpdateActualValueTarget() {
        List<Map<String, String>> list = targetValueMapper.getUpdateActualValueTarget();
        int i = 0;
        for (Map<String, String> map : list) {
            String acctYear = ObjectUtils.toString(map.get("acctYear"), "");
            String quarterCode = ObjectUtils.toString(map.get("quarterCode"), "");
            String compCode = ObjectUtils.toString(map.get("compCode"), "");
            String targetNo = ObjectUtils.toString(map.get("targetNo"), "");
            String targetName = ObjectUtils.toString(map.get("targetNo"), "");
            String targetValue = ObjectUtils.toString(map.get("targetValue"), "");
            if (!StringUtils.isBlank(targetNo) && !StringUtils.isBlank(acctYear) && !StringUtils.isBlank(quarterCode)) {
                updateReferenceValue(targetNo, targetName, compCode, acctYear, quarterCode, targetValue);
            }
        }
    }

    /**
     * @param targetNo 指标编码
     * @param compCode 公司编码
     * @return
     * @description 根据指标编码和公司获取最新的TargetValue数据记录
     * @author CuiShiHao
     */
    @Override
    public ZbaaTargetValue getLastZbaaTargetInfo(String targetNo, String compCode) {
        // ----待修改
        List<ZbaaTargetValue> targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNo, null , compCode, null, "1");
        ZbaaTargetValue zbaaTarget = targetValueList.size() > 0 ? targetValueList.get(0) : null;
        return zbaaTarget;
    }

    /**
     * @param targetNo
     * @return
     * @description 获取订阅指标数据的部门
     * @author CuiShiHao
     */
    @Override
    public List<XtzyCompany> getXtzyCompanyByTargetNo(String targetNo) {
        List<XtzyCompany> result = targetValueMapper.getXtzyCompanyByTargetNo(targetNo);
        return result;
    }

    @Override
    public List<ZbaaTarget> getTargetListByTagertTypesAndUserComp(ZbaaTarget target, List<String> ddCodeList, XtzyUser user) {
        List<ZbaaTarget> targetList = targetMapper.getTargetListByTagertTypesAndUserComp(target, ddCodeList, user.getExt1());
        //sendInfo(targetList, user.getUserCode());
        return targetList;
    }

    /**
     * @description 首页行业需求指标
     * @author CuiShiHao
     */
    @Override
    public List<ZbaaTargetHomeIndexVO> getHomeIndex() {
        List<ZbaaTargetHomeIndexVO> resultList = new ArrayList<>();

        // 页面上展示的指标targetNo:按顺序写死
        // 社会融资同比增幅，制造业PMI同比增幅,国内生产总值月度GDP，国内汽车销量，房地产当月销量
        // 普氏62%铁矿石指数,CR炼焦煤价格指数,中国粗钢产量,钢铁社会库存总量,供需平衡
        // 指标对应的组织 Wind SSB MySteel
        List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0009", "ZBW0034", "ZBW0005", "ZBW0049", "ZBW0236", "ZBW0055", "ZBW0158", "ZBW0059", "ZBW0064", "ZBW0000"));
        List<String> targetPeriodList = new ArrayList<>(Arrays.asList("月", "月", "季", "月", "月", "日", "日", "月", "日", "季"));
        List<String> sysSourceList = new ArrayList<>(Arrays.asList("Y", "Wind", "Wind", "CPCA", "SSB", "Wind", "Bsteel", "Wind", "Bsteel", "G"));
        // 同比上年数据处理，同比为Y，环比N
        List<String> compareList = new ArrayList<>(Arrays.asList("Y", "N", "Y", "Y", "Y", "N", "N", "Y", "N", "Y"));
        for (int i = 0; i < targetNoList.size(); i++) {

            ZbaaTargetHomeIndexVO resultVO = new ZbaaTargetHomeIndexVO();

            // 插入指标定义
            ZbaaTarget zbaaTarget = targetMapper.getTargetByTargetNo(targetNoList.get(i));
            if (zbaaTarget != null) {
                resultVO.setDefinition(zbaaTarget.getTargetDesc());
            }

            // 获取当前指标最新的指标数据
            List<ZbaaTargetValue> targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i), null, null, "2");
            ZbaaTargetValue latestValue = targetValueList.size() > 0 ? targetValueList.get(0) : null;
            ZbaaTargetValue previousValue = targetValueList.size() > 1 ? targetValueList.get(1) : null;

            if (latestValue == null) {
                // 最新指标数据无结果，则全部填-
                resultVO.setValue("-");
                resultVO.setRate("-");
                resultVO.setStatus("-");
                resultVO.setRemark("<br/>当前指标无数据");
                resultVO.setStatisticsTime("-");
                resultList.add(resultVO);
                continue;
            }

            // 判断是否同比，更新previousValue信息。
            String latestPeriod = latestValue.getPeriodNo();
            if (compareList.get(i).equals("Y")) {
                int year = Integer.parseInt(latestPeriod.substring(0, 4)) - 1;
                String perviousPeriodNo = String.valueOf(year) + latestPeriod.substring(4, latestPeriod.length());
                List<ZbaaTargetValue> valueList = targetValueMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i),null, perviousPeriodNo, "1");
                previousValue = valueList.size() > 0 ? valueList.get(0) : null;
            }

            if (previousValue == null) {
                // 上一条数据无结果，则填-
                resultVO.setValue(latestValue.getTargetValue());
                resultVO.setRate("-");
                resultVO.setStatus("-");
                resultVO.setSource(latestValue.getSysSourceName());
                resultVO.setCreateTime(latestValue.getCreateTime());
                String remark = "<br/>" + latestPeriod + "数据值：" + latestValue.getTargetValue() + "</br>";
                resultVO.setRemark(remark);
                resultVO.setStatisticsTime(latestPeriod);
                resultList.add(resultVO);
                continue;
            }

            // 常规计算
            double currentData = Double.parseDouble(latestValue.getTargetValue());
            double lastData = Double.parseDouble(previousValue.getTargetValue());

            // 状态为1是上升，0位下降。
            String status = currentData - lastData >= 0 ? "1" : "0";
            String rate = String.valueOf(Math.abs(currentData - lastData) / Math.abs(lastData));
            resultVO.setValue(String.valueOf(currentData));
            resultVO.setRate(rate);
            resultVO.setStatus(status);
            resultVO.setSource(latestValue.getSysSourceName());
            resultVO.setCreateTime(latestValue.getCreateTime());
            String remark = "<br/>" + latestPeriod + "数据值：" + currentData + "</br>";
            remark += previousValue.getPeriodNo() + "数据值：" + lastData;
            resultVO.setRemark(remark);
            resultVO.setStatisticsTime(latestPeriod);
            resultList.add(resultVO);
        }
        System.out.println(resultList);
        return resultList;
    }


    /**
     * @description 首页行业需求指标状态
     * @author CuiShiHao
     */
    @Override
    public JSONObject getHomeIndexStatus() {
        // 页面上展示的指标targetNo:按顺序写死的
        // 社会融资增速，制造业PMI, GDP增速，汽车销量，房产销量
        List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0009", "ZBW0034", "ZBW0005", "ZBW0049", "ZBW0236"));
        List<String> sysSourceList = new ArrayList<>(Arrays.asList("Y", "Wind", "Wind", "CPCA", "SSB"));

        List<String> dataList = new ArrayList<>();
        List<String> remarkList = new ArrayList<>();
        List<String> statusList = new ArrayList<>();
        // 获取当前指标最新的指标数据
        for (int i = 0; i < targetNoList.size(); i++) {
            List<ZbaaTargetValue> targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i), null, null, "1");
            ZbaaTargetValue latestValue = CollectionUtils.isNotEmpty(targetValueList) ? targetValueList.get(0) : new ZbaaTargetValue();
            dataList.add(StringUtils.isEmpty(latestValue.getStabilityName()) ? "" : latestValue.getStabilityName());
            remarkList.add(StringUtils.isEmpty(latestValue.getValuePeriodRange()) ? "" : latestValue.getValuePeriodRange());
            statusList.add(StringUtils.isEmpty(latestValue.getStabilityCode()) ? "" : latestValue.getStabilityCode());

        }
        Map<String, Object> maps = new HashMap<>();
        maps.put("data", dataList);
        maps.put("remark", remarkList);
        maps.put("status", statusList);
        System.out.println(maps);

        return JSONObject.fromObject(maps);
    }

    /**
     * @description 首页行业需求指标状态（从Python获取计算结果）
     * @author CuiShiHao
     */
    @Override
    public JSONObject getHomeIndexStatusFromPython(String params, String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;

        JSONObject object = null;
        try {
            List<List<String>> queryDataList = new ArrayList<>();

            // 页面上展示的指标targetNo:按顺序写死的
            // 社会融资增速，制造业PMI, GDP增速，汽车销量，房产销量
            List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0009", "ZBW0034", "ZBW0005", "ZBW0049", "ZBW0236"));
            List<String> sysSourceList = new ArrayList<>(Arrays.asList("Y", "Wind", "Wind", "CPCA", "SSB"));

            for (int i = 0; i < targetNoList.size(); i++) {
                List<ZbaaTargetValue> valueList = new ArrayList<>();
                //由于国内汽车销量的数据的变动,指标值单位也要统一进行计算(钢管条钢事业部,全部,取全部CodeName为全部的)
                if ("ZBW0049".equals(targetNoList.get(i))){
                    valueList = targetValueMapper.getHistoryOfCar(targetNoList.get(i), 100);
                }else {
                    valueList  = targetValueMapper.getHistory(targetNoList.get(i), 100);
                }
                System.out.println("size: "+valueList.size());
                List<String> result = new ArrayList<>();
                for (ZbaaTargetValue zbaaTargetValue : valueList) {
                    String value = zbaaTargetValue.getTargetValue();
                    result.add(value);
                }
                queryDataList.add(result);
            }

            Map<String, Object> maps = new HashMap<>();
            maps.put("data", queryDataList);
            try {
                // 调用Python接口
                String url = ReadProperties.getValueString("python.threshold.url");
                String result = HttpUtils.sendJsonPost(url, JSONObject.fromObject(maps));

                if (StringUtils.isNotEmpty(result)) {
                    object = JSONObject.fromObject(result);
                    System.out.println("预测结果：" + result);
                    List<String> dataList = JSONArray.toList(object.getJSONArray("data"), new String(), new JsonConfig());
                    List<String> remarkList = JSONArray.toList(object.getJSONArray("remark"), new String(), new JsonConfig());
                    List<String> statusList = JSONArray.toList(object.getJSONArray("status"), new String(), new JsonConfig());
                    //新增到扩展字段的趋势
                    List<String> stabilityList = JSONArray.toList(object.getJSONArray("stability"), new String(), new JsonConfig());
                    // 解析返回的数据结果，将结果更新到value表中
                    // 获取当前指标最新的指标数据
                    for (int i = 0; i < targetNoList.size(); i++) {
                        List<ZbaaTargetValue> targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSourceList.get(i), null, null, "1");
                        ZbaaTargetValue latestValue = CollectionUtils.isNotEmpty(targetValueList) ? targetValueList.get(0) : new ZbaaTargetValue();
                        latestValue.setStabilityName(dataList.get(i));
                        latestValue.setValuePeriodRange(remarkList.get(i));
                        latestValue.setStabilityCode(statusList.get(i));
                        latestValue.setExt2(stabilityList.get(i));
                        latestValue.setUpdateTime(new Date());
                        targetValueMapper.updateByPrimaryKey(latestValue);
                    }
                }

                logs.add(fltdProcessService.getLog("首页行业需求指标状态获取定时任务执行成功", 0, "", jobId));

            } catch (Exception e) {
                error = e;
                logs.add(fltdProcessService.getLog("首页行业需求指标状态获取定时任务执行失败", 1, e.getMessage(), jobId));
                log.error("首页行业需求指标状态调用PYTHON接口出错");
            }
        }catch (Exception e) {
            error = e;
            logs.add(fltdProcessService.getLog("首页行业需求指标状态获取定时任务执行失败", 1, e.getMessage(), jobId));
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
        return object;
    }

    @Override
    public List<List<ZbaaTargetValueVO>> getHomeIndexDataList() {
        List<List<ZbaaTargetValueVO>> resultList = new ArrayList<>();

        // 页面上展示的指标数据targetNo:按顺序写死
        // 工业生产者出厂价格指数（PPI）,Mysteel钢材综合价格指数, 西本新干线钢材指数,
        // 普氏62%铁矿石指数,CR炼焦煤价格指数,中国粗钢产量,钢铁社会库存总量
        List<String> targetNoList = new ArrayList<>(Arrays.asList("ZBW0033", "ZBW0106", "ZBW0146", "ZBW0055", "ZBW0158", "ZBW0059", "ZBW0064"));
        List<String> targetPeriodList = new ArrayList<>(Arrays.asList("月", "日", "日", "日", "日", "月", "日"));
        List<String> wind = new ArrayList<>(Arrays.asList("Wind"));
        List<String> ssb = new ArrayList<>(Arrays.asList("SSB"));
        List<String> mysteel = new ArrayList<>(Arrays.asList("Mysteel"));
        List<String> bsteel = new ArrayList<>(Arrays.asList("Bsteel"));
        List<List<String>> sysSourceList = new ArrayList<>(Arrays.asList(wind, bsteel, wind, wind, bsteel, wind, bsteel));

        for (int i = 0; i < targetNoList.size(); i++) {
            String targetNo = targetNoList.get(i);
            String period = targetPeriodList.get(i);

            String sysSource = sysSourceList.get(i).get(0);
            // 获取当前指标最新的指标更新时间
            List<ZbaaTargetValue> targetValueList = new ArrayList<>();
            if ("ZBW0106".equals(targetNo)){
                targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSource, "BGTA", null, "1");
            }else {
                targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNoList.get(i), sysSource, null, null, "1");
            }

            ZbaaTargetValue latestValue = targetValueList.size() > 0 ? targetValueList.get(0) : null;
            if (latestValue == null) {
                // 无数据则添加一条对应的空数组记录
                List<ZbaaTargetValueVO> result = new ArrayList<>();
                resultList.add(result);
                continue;
            }

            String endTime = latestValue.getPeriodNo();
            if (targetPeriodList.get(i).equals("月")) {
                endTime = endTime + "01";
            }
            //将endTime格式YYYYMMDD改写成YYYY-MM-DD
            endTime = endTime.substring(0, 4) + "-" + endTime.substring(4, 6) + "-" + endTime.substring(6, 8);

            String interval = "10";
            String startTime = DateUtils.caculateTime(endTime, period, interval);
            List<ZbaaTargetValueVO> result = getHomeValue(targetNo, sysSourceList.get(i), startTime, endTime, period);
            resultList.add(result);
        }
        System.out.println(resultList);
        return resultList;
    }

    @Override
    public JSONObject getAnaylzeResult(Map<String, Object> maps) {
        System.out.println(maps.get("data"));
        // 调用Python接口
        String url = ReadProperties.getValueString("python.corr.url");
        //调用外部接口获取数据
        String result = HttpUtils.sendJsonPost(url, JSONObject.fromObject(maps));
        System.out.println("------------------------------>>>>>>>>"+result);
        String data = result.replace("[","").replace("]","");
        if ("".equals(data)){
            return null;
        }
        JSONObject jsonResult = JSONObject.fromObject(result);


        return jsonResult;
    }

    @Override
    public void calculateTarget(String startDate, String endDate) throws Exception {
        DateFormat format = new SimpleDateFormat("yyyyMMdd");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            Date start = format.parse(startDate);
            Date end = format.parse(endDate);
            long diff = end.getTime() - start.getTime();//这样得到的差值是微秒级别
            long days = diff / (1000 * 60 * 60 * 24);
            if (days == 0) {
                calculate(start);
            } else if (days > 0) {
                for (int i = 0; i < days + 1; i++) {
                    Calendar c = Calendar.getInstance();
                    c.setTime(start);
                    c.set(Calendar.DATE, c.get(Calendar.DATE) + i);
                    calculate(c.getTime());//根据时间计算
                }
            } else {
                throw new Exception("开始时间大于结束时间，请重新选择时间！");
            }
        } else {
            calculate(new Date());
        }
    }


    public void calculate(Date date) {
        //找到需要计算的指标,指标公式不为空
        List<ZbaaTarget> targetList = targetMapper.getTargetByJiSuan();
//        List<ZbaaTarget> targetList = new ArrayList<>();
//        targetList.add(targetMapper.selectByPrimaryKey("ZBW0212"));
        if (CollectionUtils.isNotEmpty(targetList)) {
            for (ZbaaTarget target : targetList) {
                String value = jisuan(target, date);
                //如果计算结果是空的，表示计算异常，开始下一个计算
                if (StringUtils.isEmpty(value)) {
                    continue;
                }
                //指标结果需要关联的公司集合
                Map<String, String> compCodeMap = new HashMap<>();
                if ("all".equals(target.getCompCode())) {
                    //找到指标中的所有指标因子
                    List<ZbaaTargetUnit> unitList = targetUnitMapper.selectByTargetId(target.getId());
                    if (CollectionUtils.isEmpty(unitList)) {
                        continue;
                    }
                    //所有指标因子的指标编号
                    List<String> targetNos = unitList.stream().map(ZbaaTargetUnit::getTargetNo).collect(Collectors.toList());
                    //根据指标编号找到所有指标值所属的组织机构
                    List<ZbaaTargetValue> compList = targetValueMapper.getCompByTarget(targetNos);
                    if (CollectionUtils.isEmpty(compList)) {
                        continue;
                    }
                    //根据组织把指标分组
                    Map<String, List<ZbaaTargetValue>> map = compList.stream().collect(Collectors.groupingBy(ZbaaTargetValue::getCompCode));
                    //遍历
                    for (String key : map.keySet()) {
                        //组织下的指标
                        List<ZbaaTargetValue> valueList = map.get(key);
                        //组织下的指标编码集合
                        List<String> codeList = valueList.stream().map(ZbaaTargetValue::getTargetNo).collect(Collectors.toList());

                        Boolean flag = true;
                        for (String targetNo : targetNos) {
                            //如果组织下不包含这个指标，返回false
                            if (!codeList.contains(targetNo)) {
                                flag = false;
                            }
                            if (!flag) {
                                continue;
                            }
                        }
                        //如果这个公司下全部包含这个指标，则为符合条件的公司
                        if (flag) {
                            compCodeMap.put(key, map.get(key).get(0).getCompName());
                        }
                    }
                } else {
                    compCodeMap.put(target.getCompCode(), target.getCompName());
                }
                System.out.println("----------" + compCodeMap.toString());
                insertValue(target, compCodeMap, value, date);
            }
        }
    }

    public Boolean insertValue(ZbaaTarget target, Map<String, String> compCodeMap, String value, Date date) {
        if (compCodeMap.isEmpty()) {
            return false;
        }
        Calendar calendar = Calendar.getInstance(); //创建Calendar 的实例
        calendar.setTime(date);
        calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) - 1); //当前时间减去一天，即一天前的时间
        String riqi = DateUtils.format(calendar.getTime(), "yyyyMMdd");
        //年
        String year = riqi.substring(0, 4);
        //月
        String mouth = riqi.substring(4, 6);
        //季
        String quarter = DateUtils.getQuarter(calendar.getTime());
        for (String code : compCodeMap.keySet()) {
            ZbaaTargetValue targetValue = new ZbaaTargetValue();
            targetValue.setCompCode(code);
            targetValue.setCompName(compCodeMap.get(code));
            targetValue.setTargetNo(target.getTargetNo());
            targetValue.setTargetName(target.getTargetName());
            targetValue.setTargetDesc(target.getTargetDesc());
            targetValue.setTargetType(target.getTargetType());
            targetValue.setTargetTypeName(target.getTargetTypeName());
            targetValue.setSysSource(target.getSysSource());
            targetValue.setSysSourceName(target.getSysSourceName());
            targetValue.setRangeCode(target.getRangeCode());
            targetValue.setRangeName(target.getRangeName());
            targetValue.setQuantityFlag(target.getQuantityFlag());
            targetValue.setUnit(target.getUnit());
            targetValue.setAcctYear(year);
            targetValue.setAcctPeriod(mouth);
            targetValue.setTargetValue(value);
            targetValue.setDdTypeCode(target.getDdTypeCode());
            targetValue.setDdTypeName(target.getDdTypeName());
            targetValue.setRiskSource(target.getRiskSource());
            targetValue.setRiskSourceName(target.getRiskSourceName());
            //如果周期是年，一年只有一条数据，已存在更新，不存在新增
            if ("yyyy".equals(target.getTargetPeriod())) {
                targetValue.setPeriodNo(year);
            } else if ("quarter".equals(target.getTargetPeriod())) {
                targetValue.setPeriodNo(year + "Q" + quarter);
            } else if ("mouth".equals(target.getTargetPeriod())) {
                targetValue.setPeriodNo(year + mouth);
                targetValue.setAcctPeriod(mouth);
            } else {
                targetValue.setPeriodNo(riqi);
                targetValue.setAcctPeriod(mouth);
            }
            targetValue.setAcctYear(year);

            List<ZbaaTargetValue> valueList = targetValueMapper.queryTargetValue(target.getTargetNo(), targetValue.getCompCode(), targetValue.getPeriodNo());

            //如果这个批号下的数据是空的，新增，不为空，修改
            if (CollectionUtils.isEmpty(valueList)) {
                targetValue = (ZbaaTargetValue) BeanUtils.initBean(targetValue);
                targetValueMapper.insert(targetValue);
            } else {
                for (ZbaaTargetValue zbaaTargetValue : valueList) {
                    targetValueMapper.deleteByPrimaryKey(zbaaTargetValue.getId());
                }
                targetValue = (ZbaaTargetValue) BeanUtils.initBean(targetValue);
                targetValueMapper.insert(targetValue);
            }
        }
        return true;
    }

    public String jisuan(ZbaaTarget target, Date date) {
        //指标公式
        String targetFormula = target.getTargetFormula();
        //指标计算==指标因子格式==targetNo&compCode&取值范围
        String[] targetUnit = targetFormula.split("#");
        //指标公式
        String result = "";
        for (String unit : targetUnit) {
            if (StringUtils.isEmpty(unit)) {
                continue;
            }
            //如果是数字，直接拼接在公式上
            if (Character.isDigit(unit.charAt(0))) {
                result = result + unit;
                continue;
            } else if (!unit.equals("+") && !unit.equals("-") && !unit.equals("*")
                    && !unit.equals("/") && !unit.equals("(") && !unit.equals(")")) {
                //如果不是符号[+,-,*,/,(,)],处理数据后，拼接在公式上
                //指标因子元素
                String[] b = unit.split("&");
                String targetNo = b[0];//第一个是指标编号->不能为空
                String compCode = null;
                String val = null;
                //如果长度是3，表示单位和取值范围都有值
                if (b.length == 3) {
                    compCode = b[1];//第二个是单位
                    val = b[2];//第三个是取值范围
                }
                //如果长度是2，表示取值范围是空
                if (b.length == 2) {
                    compCode = b[1];
                }
                //根据参数去找结果
                String value = getTargrtValue(date, targetNo, compCode, val);
                if (StringUtils.isEmpty(value)) {
                    return null;
                }
                result = result + value;
                continue;
            } else {
                //如果是符号[+,-,*,/,(,)],直接拼接在公式上
                result = result + unit;
            }
        }

        System.out.println("公式-----------" + result);
        String resultValue = "";
        //把字符串公式转换成数学公式
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        try {
            //根据公式计算出结果
            resultValue = String.valueOf(jse.eval(result));
        } catch (ScriptException e) {
            log.error(e.getMessage());
            return null;
        }
        System.out.println("结果=============" + resultValue);
        return resultValue;
    }

    @Override
    public List<ZbaaTarget> getTargetListByRiskSource(String riskSource) {
        List<ZbaaTarget> result = targetMapper.getTargetListByRiskSource(riskSource);
        return result;
    }

    /**
     * @description 定时任务计算复合型指标
     * @author CuiShiHao
     * @date 2019/10/23
     */
    @Override
    public void calculateTargetByTask(String params, String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            // 获取全部复合型指标类型
            List<ZbaaTarget> targetList = targetMapper.getTargetByJiSuan();

            if (CollectionUtils.isNotEmpty(targetList)) {
                for (ZbaaTarget target : targetList) {
                    // 获取指标公式，指标因子格式==targetNo&compCode&取值范围
                    String targetFormula = target.getTargetFormula();
                    List<String> targetUnit = new ArrayList<>(Arrays.asList(targetFormula.split("#")));
                    //获取最后的那条符合指标数据
                    List<ZbaaTargetValue> valueList = targetValueMapper.getLastZbaaTargetInfo(target.getTargetNo(), null, target.getCompCode(),null,"1");

                    // 解析指标公式中传入的计算因子信息
                    List<String> targetNoList = new ArrayList<>();
                    List<String> compCodeList = new ArrayList<>();
                    for (String unit : targetUnit) {
                        if (unit.length() > 1 && !Character.isDigit(unit.charAt(0))) {
                            //由于钢铁社会库存 断点试验   这里unit.split("&"); 有时分成3段 第三段才是compCode
                            String[] infoList = unit.split("&");
                            targetNoList.add(infoList[0]);
                            compCodeList.add(infoList[1]);
                        }
                    }

                    String targetValuePeriodNo = "";
                    // 校验指标公式中传入的指标，最新周期是否相等，是否能够满足计算条件。
                    for (int i = 0; i < targetNoList.size(); i++) {
                        String targetNo = targetNoList.get(i);
//                        ZbaaTarget zbaaTarget = targetMapper.getTargetByTargetNo(targetNo);
                        String compCode = compCodeList.get(i);
                        if (StringUtils.isEmpty(compCode)) {
                            break;
                        }
                        List<ZbaaTargetValue> targetValueList = targetValueMapper.getLastZbaaTargetInfo(targetNo, null, compCode, null, "1");

                        if (targetValueList.size() == 0) {
                            targetValuePeriodNo = "";
                            break;
                        }
                        if (i == 0) {
                            targetValuePeriodNo = targetValueList.get(0).getPeriodNo();
                        } else {
                            targetValuePeriodNo = targetValuePeriodNo.compareTo(targetValueList.get(0).getPeriodNo()) < 0 ? targetValuePeriodNo : targetValueList.get(0).getPeriodNo();
                        }
                    }

                    System.out.println(targetValuePeriodNo);

                    // 以下几种情况数据条件不满足计算，跳过当前复合型指标值的计算
                    // 1、获取的计算因子时间最小公约数为空
                    // 2、需要计算的复合型指标数据来源单位为空
                    if (StringUtils.isEmpty(targetValuePeriodNo) || (StringUtils.isEmpty(target.getSysSource()) && StringUtils.isEmpty(target.getCompCode()) )) {
                        continue;
                    }
                    // 3、计算因子时间最小公约数，小于复合型指标PeriodNo。则不需要计算
                    if (valueList.size() > 0 && valueList.get(0).getPeriodNo().compareTo(targetValuePeriodNo) > 0) {
                        continue;
                    }

                    //重新解析拼接指标公式
                    String result = "";
                    for (String unit : targetUnit) {
                        if (StringUtils.isEmpty(unit)) {
                            continue;
                        }
                        //如果是数字，直接拼接在公式上
                        if (Character.isDigit(unit.charAt(0))) {
                            result = result + unit;
                            continue;
                        }
                        //如果不是符号[+,-,*,/,(,)],处理指标因子信息，拼接在公式上
                        else if (!unit.equals("+") && !unit.equals("-") && !unit.equals("*")
                                && !unit.equals("/") && !unit.equals("(") && !unit.equals(")")) {

                            //指标因子元素
                            String[] info = unit.split("&");
                            //指标编号-组织编码-取值范围
                            String targetNo = info[0];
                            String compCode = info[1];
                            String val = info[2];

                            //根据参数去找结果
                            String value = getTargrtValueByTask(targetValuePeriodNo, targetNo, compCode, val);
                            if (value == null || StringUtils.isEmpty(value)) {
                                result = "";
                                // System.out.println("指标" + targetNo + "周期" + targetValuePeriodNo + "单位" + compCode + "计算期间" + val + "无数据");
                                break;
                            }
                            System.out.println(value);
                            result = result + value;
                            continue;
                        } else {
                            //如果是符号[+,-,*,/,(,)],直接拼接在公式上
                            result = result + unit;
                        }
                    }

                    // 进行公式计算
                    if (StringUtils.isNotEmpty(result)) {
                        System.out.println("公式-----------" + result);
                        String resultValue = "";
                        //把字符串公式转换成数学公式
                        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
                        try {
                            //根据公式计算出结果
                            resultValue = String.valueOf(jse.eval(result));
                        } catch (ScriptException e) {
                            log.error(e.getMessage());
                        }
                        System.out.println("结果=============" + resultValue);

                        // 插入计算结果指标数据值
                        ZbaaTargetValue targetValue = new ZbaaTargetValue();
                        targetValue.setId(UUID.randomUUID().toString());
                        targetValue.setTargetNo(target.getTargetNo());
                        targetValue.setTargetName(target.getTargetName());
                        targetValue.setTargetDesc(target.getTargetDesc());
                        targetValue.setTargetPeriodName(target.getTargetPeriodName());
                        targetValue.setTargetPeriod(target.getTargetPeriod());
                        targetValue.setSysSource(target.getSysSource());
                        targetValue.setSysSourceName(target.getSysSourceName());
//                        if (target.getCompCode() == null || target.getCompCode().equals("")) {
//                            // 如果没有选择单位，则用单位来源赋值
//                            targetValue.setCompCode(target.getSysSourceName());
//                        } else {
//                            // 如果选择单位，则用单位CompCode赋值
//                            targetValue.setCompCode(target.getCompCode());
//                        }
                        targetValue.setCompCode(target.getCompCode());
                        targetValue.setCompName(target.getCompName());
                        targetValue.setUnit(target.getUnit());
                        targetValue.setAcctYear(targetValuePeriodNo.substring(0, 4));
                        if (targetValuePeriodNo.length() > 4) {
                            targetValue.setAcctPeriod(targetValuePeriodNo.substring(4, 6));
                        }
                        targetValue.setPeriodNo(targetValuePeriodNo);
                        targetValue.setTargetValue(resultValue);
                        targetValue.setCreateTime(new Date());
                        targetValue.setUpdateTime(new Date());
                        targetValue.setRiskSource(target.getRiskSource());
                        targetValue.setRiskSourceName(target.getRiskSourceName());
                        targetValueMapper.insert(targetValue);
                    }
                }
            }
            logs.add(fltdProcessService.getLog("复合型指标计算定时任务执行成功", 0, "", jobId));
        }catch (Exception e) {
            error = e;
            logs.add(fltdProcessService.getLog("复合型指标计算定时任务执行失败", 1, e.getMessage(), jobId));
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }

    /**
     * @description 定时任务计算复合型指标(根据传递的指标因子信息获取数据值)
     * @author CuiShiHao
     * @date 2019/10/23
     */
    public String getTargrtValueByTask(String periodNo, String targetNo, String compCode, String val) {

        ZbaaTarget zbaaTarget = targetMapper.getTargetByTargetNo(targetNo);
        String periodName = zbaaTarget.getTargetPeriodName();

        // 将当前periodNo按照当前指标周期处理
        String dateTime = "";
        if ("季".equals(periodName)) {
            String year = periodNo.substring(0, 4);
            String quarter = periodNo.substring(5, 6);
            switch (quarter) {
                case "1":
                    dateTime = year + "0101";
                    break;
                case "2":
                    dateTime = year + "0401";
                    break;
                case "3":
                    dateTime = year + "0701";
                    break;
                case "4":
                    dateTime = year + "1001";
                    break;
            }
        } else if ("月".equals(periodName)) {
            dateTime = periodNo + "01";
        } else if ("年".equals(periodName)) {
            dateTime = periodNo + "0101";
        } else {
            dateTime = periodNo;
        }

        //创建 Calendar实例
        Date date = DateUtils.parse(dateTime, DateUtils.YYYYMMDD);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        Integer year = calendar.get(Calendar.YEAR);
        String mouth = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        Integer quarter = Integer.valueOf(DateUtils.getQuarter(calendar.getTime()));
        // 当月天数
        Integer dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        //季度月份
        List<String> mouthList = new ArrayList<>();

        // 计算结果当前值
        String flag = "";
        if (StringUtils.isNotEmpty(val)) {
            switch (val) {
                case "0010":
                    // 当前值
                    flag = periodNo;
                    break;
                case "0M01":
                    //月度最后一天（本月最后一天）
                    flag = dateTime.substring(0, 6) + dayCount.toString();
                    break;
                case "0Q01":
                    //季度最后一天（本季度最后一天）
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    mouth = mouthList.get(mouthList.size() - 1);
                    if ("03".equals(mouth) || "12".equals(mouth)) {
                        flag = year.toString() + mouth + "31";
                    } else {
                        flag = year.toString() + mouth + "30";
                    }
                    break;
                case "0Q02":
                    //季度最后一个月（本季度最后一月）
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    mouth = mouthList.get(mouthList.size() - 1);
                    if (mouth.length() < 2) {
                        flag = year.toString() + "0" + mouth;
                    } else {
                        flag = year.toString() + mouth;
                    }
                    break;
                case "0Q03":
                    //本季度平均值
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    mouthList.add("Q" + quarter.toString());
                    return targetValueMapper.getAverageValue(targetNo, compCode, year.toString(), mouthList);
                case "0Y01":
                    //年度最后一天
                    flag = year.toString() + "1231";
                    break;
                case "SumQ":
                    // 月度季度求和
                    return targetValueMapper.getSumValue(targetNo, compCode, year.toString(), mouthList);
                case "LQ01":
                    //上季度最后一天
                    if (1 == quarter) {
                        year = year - 1;
                        quarter = 4;
                    } else {
                        quarter = quarter - 1;
                    }
                    mouth = dateTime.substring(4, 6);
                    DateUtils.getQuarterMouth(quarter, mouthList);
                    if ("03".equals(mouth) || "12".equals(mouth)) {
                        flag = year.toString() + mouthList.get(mouthList.size() - 1) + "31";
                    } else {
                        flag = year.toString() + mouthList.get(mouthList.size() - 1) + "30";
                    }
                    break;
                case "LM00":
                    // 上月值
                    calendar.add(Calendar.MONTH, -1);//当前时间前去一个月，即一个月前的时间
                    dateTime = DateUtils.format(calendar.getTime(), "yyyyMMdd");
                    flag = dateTime.substring(0, 6);
                    break;
                case "LM01":
                    //上月度最后一天
                    calendar.add(Calendar.MONTH, -1);//当前时间前去一个月，即一个月前的时间
                    dateTime = DateUtils.format(calendar.getTime(), "yyyyMMdd");
                    dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
                    flag = dateTime.substring(0, 6) + dayCount.toString();
                    break;
                case "LY01":
                    //上年度最后一天
                    year = year - 1;
                    flag = year.toString() + "1231";
                    break;
                case "LY02":
                    //上年本月
                    year = year - 1;
                    flag = year + periodNo.substring(4, 6);
                    break;
                case "LY03":
                    // 上年本季度
                    year = year - 1;
                    flag = year.toString() + periodNo.substring(4, 6);
                    break;
                default:
                    //最新的数据
                    System.out.println("计算编码未添加");
                    break;
            }
        }
        System.out.println("flag" + flag);
        String value = targetValueMapper.getLatestValue(targetNo, compCode, flag, null);
        return value;
    }

    @Override
    public List<PersonTargetTreeVO> getTargetTree(String queryFlag) {

        // 当前登录人所属公司近年来的披露报告指标
        Map<String, ZbaaTarget> reportTargetMap = getReportTagert(queryFlag);

        // 指标树
        List<PersonTargetTreeVO> tree = new ArrayList<>();

        // 保存父子结构的值集
        Map<String, List<XtaaCode>> parentMap = new HashMap<>();

        // 保存层级结构的值集
        Map<String, List<XtaaCode>> levelMap = new HashMap<>();

        // 保存叶子节点的值集
        Map<String, PersonTargetTreeVO> leafMap = new HashMap<>();

        // 指标的值集
        List<XtaaCode> treeList = xtaaCodeService.selectAllDataByDDTypeCode("RIAA_ZB_CLASS");

        // 把字典数据转换成map
        Map<String, XtaaCode> xtaaCodeMap = new HashMap<>();
        for (XtaaCode xtaaCode : treeList) {
            xtaaCodeMap.put(xtaaCode.getDdCode(), xtaaCode);
        }

        // 构建指标树
        buildCodeTree(reportTargetMap, parentMap, levelMap, leafMap, tree, xtaaCodeMap, "0", queryFlag);

        // 构建叶子节点
        buildLeaf(leafMap);

        return tree;
    }

    @Override
    public List<ZbaaTarget> getRiskWarningStatusTargetList(ZbaaTarget target) {
        return targetMapper.getRiskWarningStatusTargetList(target);
    }

    private Map<String, ZbaaTarget> getReportTagert(String queryFlag) {
        Map<String, ZbaaTarget> reportTargetMap = new HashMap<>();
        if ("person".equals(queryFlag)) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.YEAR, -1);
            String acctYear = DateUtils.format(calendar.getTime(), "YYYY");

            // 获取当前登录人所在公司，近年来所有的披露报告指标
            List<ZbaaTarget> reportTargetList = waringService.getTargetByImport(acctYear, getUser().getExt1(), "");

            for (ZbaaTarget zbaaTarget : reportTargetList) {
                reportTargetMap.put(zbaaTarget.getTargetType(), zbaaTarget);
            }
        }
        return reportTargetMap;
    }

    /**
     * 构建指标树
     * @param tree 树
     * @param xtaaCodeMap 指标的值集
     * @param parentGuid 父节点
     */
    private void buildCodeTree(
            Map<String, ZbaaTarget> reportTargetMap,
            Map<String, List<XtaaCode>> parentMap,
            Map<String, List<XtaaCode>> levelMap,
            Map<String, PersonTargetTreeVO> leafMap,
            List<PersonTargetTreeVO> tree,
            Map<String, XtaaCode> xtaaCodeMap,
            String parentGuid,
            String queryFlag
    ) {
        for (String key : xtaaCodeMap.keySet()) {
            XtaaCode xtaaCode = xtaaCodeMap.get(key);
            if (xtaaCode.getParentGuid().equals(parentGuid)) {
                PersonTargetTreeVO personTargetTreeVO = new PersonTargetTreeVO();
                personTargetTreeVO.setNodeType("code");
                personTargetTreeVO.setXtaaCode(xtaaCode);
                personTargetTreeVO.setLabel(xtaaCode.getDdName());

                // 是否末级
                if ("1".equals(xtaaCode.getIsEndLevel())) {
                    personTargetTreeVO.setLeaf(true);
                    //根据指标过滤，只展示有指标的节点(内部指标)
                    if ("person".equals(queryFlag) && xtaaCode.getDdCode().startsWith("ZBN")) {
                        if (reportTargetMap.isEmpty()) {
                            break;
                        } else if(reportTargetMap.containsKey(xtaaCode.getDdCode())) {
                            tree.add(personTargetTreeVO);
                            leafMap.put(xtaaCode.getDdCode(), personTargetTreeVO);
                        }
                    } else {
                        tree.add(personTargetTreeVO);
                        leafMap.put(xtaaCode.getDdCode(), personTargetTreeVO);
                    }
                } else {
                    personTargetTreeVO.setLeaf(false);
                    tree.add(personTargetTreeVO);
                }

                pushOtherMap(parentMap, parentGuid, xtaaCode);
                pushOtherMap(levelMap, String.valueOf(xtaaCode.getPathLevel()), xtaaCode);


                ArrayList<PersonTargetTreeVO> children = new ArrayList<>();
                buildCodeTree(reportTargetMap, parentMap, levelMap, leafMap, children, xtaaCodeMap, xtaaCode.getId(), queryFlag);
                if (CollectionUtils.isNotEmpty(children)) {
                    personTargetTreeVO.setChildren(children);
                }
            }
        }
    }

    /**
     * 添加父子机构，层级机构
     *
     */
    private void pushOtherMap(Map<String, List<XtaaCode>> otherMap, String key, XtaaCode code) {
        List<XtaaCode> list = null;
        if (otherMap.containsKey(key)) {
            list = otherMap.get(key);
        } else {
            list = new ArrayList<>();
        }
        list.add(code);
        otherMap.put(key, list);
    }

    /**
     * 构建叶子节点的指标
     * @param leafMap 叶子节点数据
     */
    private void buildLeaf(Map<String, PersonTargetTreeVO> leafMap) {
        for (String key : leafMap.keySet()) {
            PersonTargetTreeVO leaf = leafMap.get(key);
            List<ZbaaTarget> resultList = null;
            if (leaf.getXtaaCode().getDdCode().startsWith("ZBN")) {
                // 内部指标
                // 查询指标分类,从重点风险中获取指标
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.YEAR, -1);
                String acctYear = DateUtils.format(calendar.getTime(), "YYYY");
                if ("code".equals(leaf.getNodeType())) {
                    resultList = waringService.getTargetByImport(acctYear, getUser().getExt1(), leaf.getXtaaCode().getDdCode());
                } else {
                    resultList = waringService.getTargetByImport(acctYear, getUser().getExt1(), leaf.getZbaaTarget().getTargetNo());
                }
            } else {
                // 外部指标
                // 获取当前选择指标的全部子数据Cod
                List<XtaaCode> list = null;
                if ("code".equals(leaf.getNodeType())) {
                    list = codeService.selectAllSubsetByDDCode(leaf.getXtaaCode().getDdCode());
                } else {
                    list = codeService.selectAllSubsetByDDCode(leaf.getZbaaTarget().getTargetNo());
                }

                List<String> ddCodeList = new ArrayList<>();
                for (XtaaCode xtaaCode : list) {
                    ddCodeList.add(xtaaCode.getDdCode());
                }
                resultList = getTargetListByTagertTypes(leaf.getZbaaTarget(), ddCodeList, getUser());
                // 按指标编码去重
//                resultList = resultList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(o-> o.getTargetNo()))), ArrayList::new));
            }

            // 拼接数据
            if (CollectionUtils.isNotEmpty(resultList)) {
                leaf.setLeaf(false);
                List<PersonTargetTreeVO> childList = new ArrayList<>();
                leaf.setChildren(childList);
                for (ZbaaTarget zbaaTarget : resultList) {
                    PersonTargetTreeVO targetNode = new PersonTargetTreeVO();
                    targetNode.setNodeType("target");
                    targetNode.setXtaaCode(leaf.getXtaaCode());
                    targetNode.setZbaaTarget(zbaaTarget);
                    targetNode.setLabel(zbaaTarget.getTargetName());
                    targetNode.setLeaf(true);
                    childList.add(targetNode);
                }
            }
        }
    }

}
